package org.itsolutions.javaBackup.ftp.handler;

import org.apache.commons.net.ftp.FTPFile;
import org.itsolutions.javaBackup.spi.backup.ftp.FTPFileWrapper;

/**
 * 
 * @author Tomas Fecko
 */
public final class FTPHelper {

	/**
	 * 
	 */
	private FTPHelper() {
	}

	/**
	 * 
	 * @param pFile ftp file
	 * @return file wrapper
	 */
	public static FTPFileWrapper createFileWrapper(FTPFile pFile) {
		FTPFileWrapper fileWrapper = new FTPFileWrapper();
		fileWrapper.setFileName(pFile.getName());
		fileWrapper.setGroup(pFile.getGroup());
		fileWrapper.setUser(pFile.getUser());
		fileWrapper.setGMT0Timestamp(pFile.getTimestamp().getTimeInMillis());
		fileWrapper.setHardLinkCount(pFile.getHardLinkCount());
		fileWrapper.setLink(pFile.getLink());
		fileWrapper.setRawListing(pFile.getRawListing());
		fileWrapper.setSize(pFile.getSize());
		if (pFile.getType() < 0 || pFile.getType() >= FTPFileWrapper.EFileType.values().length) {
			fileWrapper.setFileType(FTPFileWrapper.EFileType.UNKNOWN_TYPE);			
		} else {
			fileWrapper.setFileType(FTPFileWrapper.EFileType.values()[pFile.getType()]);
		}
		if (pFile.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)) {
			fileWrapper.addPermission(FTPFileWrapper.EFilePermision.USER_CAN_READ);
		}
		if (pFile.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)) {
			fileWrapper.addPermission(FTPFileWrapper.EFilePermision.USER_CAN_WRITE);
		}
		if (pFile.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)) {
			fileWrapper.addPermission(FTPFileWrapper.EFilePermision.USER_CAN_EXECUTE);
		}
		if (pFile.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)) {
			fileWrapper.addPermission(FTPFileWrapper.EFilePermision.GROUP_CAN_READ);
		}
		if (pFile.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION)) {
			fileWrapper.addPermission(FTPFileWrapper.EFilePermision.GROUP_CAN_WRITE);
		}
		if (pFile.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)) {
			fileWrapper.addPermission(FTPFileWrapper.EFilePermision.GROUP_CAN_EXECUTE);
		}
		if (pFile.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)) {
			fileWrapper.addPermission(FTPFileWrapper.EFilePermision.WORLD_CAN_READ);
		}
		if (pFile.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION)) {
			fileWrapper.addPermission(FTPFileWrapper.EFilePermision.WORLD_CAN_WRITE);
		}
		if (pFile.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)) {
			fileWrapper.addPermission(FTPFileWrapper.EFilePermision.WORLD_CAN_EXECUTE);
		}
		return fileWrapper;
	}
}
